#include "bconf.h"
#include "bio.h"
#include "bparser.h"
#include "blex.h"
#include "bmem.h"
#include "bvm.h"

#ifdef DEBUGINFO
char *codestr[] = {"mov", "add", "set", "read", "write", "loop", "end"};
#endif

#define WELCOMESTR "BrainFun 0.0.4 2018 Allen Ng\n"

void usage (void) {
	fprintf(stderr,"Usage:"
	        "brainfun file\n"
	        " file\tthe brainfun source code to run.");
}

int main(int argc, char* argv[]) {
	printf(WELCOMESTR);
	if(argc != 2) {
		usage();
	} else {
		char* filename = argv[1];
		FILE* input = fopen(filename, "r");
		if(input == NULL) {
			printf("Error: Failed to open the file %s.\n", filename);
		} else {
			LState *ls = bf_new(LState);
			IGT *i = bf_new(IGT);
			Proto* ps = bf_new(Proto);
			initLState(ls, iopen(i, input, filename));
			initProto(ps);
			parse(ps, ls);
#ifdef DEBUGINFO
			printf("compiled opcode:\n");
			int iter;
			for(iter = 0; ps->code[iter].t != EOS; iter++) {
				printf("%d)\t:(%s, %d)\n", iter, codestr[ps->code[iter].t - 1]
				,ps->code[iter].extra);
			}
#endif
			if(ps->error > 0) {
				printf("Total %d error(s) found.\n", ps->error);
			} else {
				execute(ps);
			}
		}
	}
	return 0;
}
